package com.ssmIntegration.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@ComponentScan({"com.ssmIntegration.mapper"})
public class MapperJavaConfig2 {


    /*
    sqlSessionFactory加入ioc容器
    mybatis -> sqlSessionFactoryBean加入ioc -> getObject() -> sqlSessionFactory
    方式2：不保留外部配置文件，全部mybatis的属性都在代码中设置
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // 指定配置文件等信息
        // 指定数据库连接池对象
        sqlSessionFactoryBean.setDataSource(dataSource);


        // 指定mybatis配置文件功能，使用代码的形式


        // 创建一个配置对象
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 配置<setting></setting>中的设置
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(Slf4jImpl.class);
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);

        // 指定配置
        sqlSessionFactoryBean.setConfiguration(configuration);

        // 设置别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.ssmIntegration.pojo");

        // 创建分页拦截器插件对象
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 设置属性对象
        Properties properties = new Properties();
        // 设置一个属性
        properties.setProperty("helperDialect", "mysql");
        // 指定配置好的属性
        pageInterceptor.setProperties(properties);
        // 指定插件
        sqlSessionFactoryBean.addPlugins(pageInterceptor);

        return sqlSessionFactoryBean;

    }

    /*
    mapper代理对象加入到ioc
    mapper代理对象的factoryBean，指定mapper接口存放的包。
    不需要再sqlSession.getMapper(xx.class)，直接找mapperScannerConfigurer即可
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.ssmIntegration.mapper");
        return mapperScannerConfigurer;
    }


}
